import { TestConfig } from '../common/testConfig.js';
import { getApiData } from '../../network/communicationConverter.js';
import { TestSimulateData } from '../testMgr/testSimulateData.js';
import { CommunicationPageData, ApiReturnStruct, NetworkParser, DataPage } from '../../network/communicationConverter.js';
import { FundAccount } from '../funds/fundAccount.js';
import {
    getFundAccountListData, getReceiveOrderData, getReceiveOrderDetailInfo,
    updateOrCreateReceiveOrder, reviewReceiveOrder, withdrawReviewAndDeleteOrder,
    getTargetObjectPendingReceiveOrderData, getTargetObjectPendingPaymentOrderData,
    getPaymentOrderData, updateOrCreatePaymentOrder, getPaymentOrderDetailInfo, reviewPaymentOrder,
    getSelfFundAccountType, createSelfFundAccountType, updateSelfFundAccountType, delSelfFundAccountType,
    updateOrCreateFundAccount,getFundAccountDetailInfo,removeFundAccount,
    getOtherFeeTypeData,createOtherFeeType,updateOtherFeeType,delOtherFeeType,
    getPendingReceiveOrderDetailInfo,getPendingPaymentOrderDetailInfo
} from '../../network/api.js';
import { Engine } from '../engine.js';
import { ReceiveOrder } from '../funds/receiveOrder.js';
import { PaymentOrder } from '../funds/paymentOrder.js';
import { MessageUtil } from '@/utils/MessageUtil.js';
import { OrderResult } from '../common/orderResult.js';
import { PendingReceiveOrder } from '../funds/pendingReceiveOrder.js';
import { PendingPaymentOrder } from '../funds/pendingPaymentOrder.js';
import { SelfDefFundAccountType } from '../funds/selfDefFundAccountType.js';
import { OtherFeeType } from '../funds/otherFeeType.js';

export class FundUiAction {
    /**
     * 获取资金账户列表数据
     * @param {Object} options
     * @param {string} options.orgId - Organization ID
     * @param {DataPage} options.pageInfo - Pagination information
     * @param {Object} [options.filter] - FundAccountFilter
     * @returns {Promise<ApiReturnStruct>}
     */
    async getFundAccountData({ orgId, pageInfo, filter = null }) {
        if (TestConfig.fundAccountTest) {
            // 模拟数据
            let simData = new CommunicationPageData();
            simData.dataList = new TestSimulateData().simFundAccount();

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            const apiData = await getApiData(
                FundAccount.fromJson,
                orgId || Engine.profile.org.orgId,
                pageInfo,
                getFundAccountListData,
                filter == null ? {} : filter.toJson(),
                true // showLoadingPage - defaulting to true as it's not specified
            );
            return apiData;
        }
    }

    /**
 * Create or update fund account
 * @param {FundAccount} fundAccount - Fund account object
 * @param {boolean} toAudit - Whether to audit after creation
 * @returns {Promise<OrderResult|null>}
 */
    async updateOrCreateFundAccount(fundAccount) {
        const res = await updateOrCreateFundAccount(
            fundAccount,
            Engine.profile.org.orgId
        );

        // Parse the result
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * Get fund account detail info
     * @param {string} accountId - The fund account ID to fetch
     * @returns {Promise<FundAccount|null>} 
     */
    async getFundAccountDetailInfo(accountId) {
        if (TestConfig.fundAccountTest) {
            // Simulate delay
            await new Promise(resolve => setTimeout(resolve, 1000));

            // Simulate data
            const testSimulateData = new TestSimulateData();
            let accountData = testSimulateData.simFundAccount();

            // Find matching element
            let account = accountData.find(item => item.id === accountId);
            if (account) {
                return account;
            }

            return testSimulateData.simFundAccount()[0];
        } else {
            let res = await getFundAccountDetailInfo({                
                orgId: Engine.profile.org.orgId,
                id: accountId
            });

            // Parse data using NetworkParser
            const apiResult = NetworkParser.parseNetworkResult(res, FundAccount.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * Remove fund account
     * @param {string} idList - Comma-separated account IDs to remove
     * @returns {Promise<any>}
     */
    async removeFundAccount(idList) {
        const res = await removeFundAccount(
            idList,
            Engine.profile.org.orgId
        );

        // Parse the result
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除资金账户失败:" + apiResult.resErr);
            return apiResult;
        }

        return apiResult;
    }

    /**
     * 获取收款单数据
     * @param {Object} options
     * @param {string} options.orgId - Organization ID
     * @param {DataPage} options.pageInfo - Pagination information
     * @param {Object} [options.filter] - Receive order filter
     * @returns {Promise<ApiReturnStruct>}
     */
    async getReceiveOrderData({ orgId, pageInfo, filter = null }) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟数据
            let simData = new CommunicationPageData();

            if (filter != null && filter['state'] == 1) {
                simData.dataList = new TestSimulateData().simReceiveOrder(null);
            } else if (filter != null && filter['state'] == 2) {
                simData.dataList = new TestSimulateData().simReviwedReceiveOrder(null);
            } else {
                simData.dataList = new TestSimulateData().simReceiveOrder(null);
                simData.dataList.push(...new TestSimulateData().simReviwedReceiveOrder(null));
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            const apiData = await getApiData(
                ReceiveOrder.fromJson,
                orgId || Engine.profile.org.orgId,
                pageInfo,
                getReceiveOrderData,
                filter,
                true // showLoadingPage - defaulting to true
            );
            return apiData;
        }
    }


    /**
     * 获取收款单详情
     * @param {string} orderId - The receive order ID to fetch
     * @returns {Promise<ReceiveOrder|null>} 
     */
    async getReceiveOrderDetailInfo(orderId) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let orderData = testSimulateData.simReceiveOrder();

            // 查找 匹配的元素
            let order = orderData.find(item => item.id === orderId);
            if (order) {
                return order;
            }

            return testSimulateData.simReceiveOrder()[0];
        } else {
            let res = await getReceiveOrderDetailInfo(orderId, Engine.profile.org.orgId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, ReceiveOrder.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 创建或更新收款单记录
     * @param {ReceiveOrder} receiveOrder - Receive order object
     * @param {boolean} toAudit - Whether to audit after creation
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreateReceiveOrder(receiveOrder, toAudit) {
        const res = await updateOrCreateReceiveOrder(receiveOrder, toAudit);
        // 解析数据，
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 审核收款单记录
     * @param {Object} options
     * @param {Array<string>} options.idList - List of order IDs to review
     * @param {string} options.orgId - Organization ID
     * @returns {Promise<any>}
     */
    async reviewReceiveOrder({
        idList,  // 数组 []
        orgId = null,
    }) {
        let res = await reviewReceiveOrder(
            idList,
            orgId ?? Engine.profile.org.orgId,
        );

        // 解析数据，利用 NetworkParser 解析分页数据
        const retData = NetworkParser.parseNetworkResult(res, null);

        return retData;
    }

    /**
     * 删除收款单记录
     * @param {Object} options
     * @param {string} options.orderId - Order ID
     * @param {DocType} options.docType - Document type
     * @returns {Promise<any|null>}
     */
    async removeReceiveOrder({
        orderId,
        docType, // DocType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });
        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除收款单据失败:" + apiResult.resErr);

            return apiResult;
        }
        return null;
    }

    /**
 * 获取用户待支付信息
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination information
 * @param {PendingReceiveOrderFilter} options.filter - Pending receive order filter
 * @returns {Promise<ApiReturnStruct>}
 */
    async getTargetObjectPendingReceiveOrderData({ orgId, pageInfo, filter }) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟数据
            let simData = new CommunicationPageData();
            simData.dataList = new TestSimulateData().simPendingReceiveOrder(null);

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            const apiData = await getApiData(
                PendingReceiveOrder.fromJson,
                orgId || Engine.profile.org.orgId,
                pageInfo,
                getTargetObjectPendingReceiveOrderData,
                filter.toJson(),
                true // showLoadingPage - defaulting to true
            );
            return apiData;
        }
    }

    /**
 * 获取用户待支付信息
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination information
 * @param {PendingPaymentOrderFilter} options.filter - Pending payment order filter
 * @returns {Promise<ApiReturnStruct>}
 */
    async getTargetObjectPendingPaymentOrderData({ orgId, pageInfo, filter }) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟数据
            let simData = new CommunicationPageData();
            simData.dataList = new TestSimulateData().simPendingPaymentOrder(null);

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            const apiData = await getApiData(
                PendingPaymentOrder.fromJson,
                orgId || Engine.profile.org.orgId,
                pageInfo,
                getTargetObjectPendingPaymentOrderData,
                filter.toJson(),
                true // showLoadingPage - defaulting to true
            );
            return apiData;
        }
    }

    /**
 * 获取付款单数据
 * @param {Object} options
 * @param {string} options.orgId - Organization ID
 * @param {DataPage} options.pageInfo - Pagination information
 * @param {Object} [options.filter] - Payment order filter
 * @returns {Promise<ApiReturnStruct>}
 */
    async getPaymentOrderData({ orgId, pageInfo, filter = null }) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟数据
            let simData = new CommunicationPageData();

            if (filter != null && filter['state'] == 1) {
                simData.dataList = new TestSimulateData().simPaymentOrder(null);
            } else if (filter != null && filter['state'] == 2) {
                simData.dataList = new TestSimulateData().simReviewedPaymentOrder(null);
            } else {
                simData.dataList = new TestSimulateData().simPaymentOrder(null);
                simData.dataList.push(...new TestSimulateData().simReviewedPaymentOrder(null));
            }

            let ret = new ApiReturnStruct();
            ret.data = simData;
            return ret;
        } else {
            const apiData = await getApiData(
                PaymentOrder.fromJson,
                orgId || Engine.profile.org.orgId,
                pageInfo,
                getPaymentOrderData,
                filter,
                true // showLoadingPage - defaulting to true
            );
            return apiData;
        }
    }

    /**
     * 创建或更新付款单记录
     * @param {PaymentOrder} paymentOrder - Payment order object
     * @param {boolean} toAudit - Whether to audit after creation
     * @returns {Promise<OrderResult|null>}
     */
    async updateOrCreatePaymentOrder(paymentOrder, toAudit) {
        const res = await updateOrCreatePaymentOrder(paymentOrder, toAudit);
        // 解析数据，
        const apiResult = NetworkParser.parseNetworkResult(res, OrderResult.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }

    /**
     * 获取付款单详情
     * @param {string} orderId - The payment order ID to fetch
     * @returns {Promise<PaymentOrder|null>} 
     */
    async getPaymentOrderDetailInfo(orderId) {
        if (TestConfig.receiptsOrderTest) {
            // 模拟延时（例如：500毫秒）
            await new Promise(resolve => setTimeout(resolve, 1000));
            /// 模拟数据
            const testSimulateData = new TestSimulateData();

            let orderData = testSimulateData.simPaymentOrder();

            // 查找 匹配的元素
            let order = orderData.find(item => item.id === orderId);
            if (order) {
                return order;
            }

            return testSimulateData.simPaymentOrder()[0];
        } else {
            let res = await getPaymentOrderDetailInfo(Engine.profile.org.orgId, orderId);

            // 解析数据，利用 NetworkParser 解析分页数据
            const apiResult = NetworkParser.parseNetworkResult(res, PaymentOrder.fromJson);

            if (apiResult.data != null) {
                return apiResult.data;
            } else {
                if (apiResult.resErr != null &&
                    typeof apiResult.resErr === 'string') {
                    MessageUtil.showErrorMsg(apiResult.resErr);
                }
                return null;
            }
        }
    }

    /**
     * 审核付款单记录
     * @param {Object} options
     * @param {Array<string>} options.idList - List of order IDs to review
     * @param {string} options.orgId - Organization ID
     * @returns {Promise<any>}
     */
    async reviewPaymentOrder({
        idList,  // 数组 []
        orgId = null,
    }) {
        let res = await reviewPaymentOrder(
            idList,
            orgId ?? Engine.profile.org.orgId,
        );

        // 解析数据，利用 NetworkParser 解析分页数据
        const retData = NetworkParser.parseNetworkResult(res, null);

        return retData;
    }

    /**
 * 删除付款单记录
 * @param {Object} options
 * @param {string} options.orderId - Order ID
 * @param {DocType} options.docType - Document type
 * @returns {Promise<any|null>}
 */
    async removePaymentOrder({
        orderId,
        docType, // DocType
    }) {
        const res = await withdrawReviewAndDeleteOrder({
            orderId: orderId,
            orderType: docType
        });
        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, null);

        if (apiResult.resErr != null &&
            typeof apiResult.resErr === 'string') {
            MessageUtil.showErrorMsg("删除付款单据失败:" + apiResult.resErr);

            return apiResult;
        }
        return null;
    }

    /**
   * 获取自定义资金账户类型列表数据
   * @param {Object} options
   * @param {string} options.orgId - Organization ID
   * @param {DataPage} options.pageInfo - Pagination information
   * @param {Object} [options.filter] - Filter conditions
   * @returns {Promise<ApiReturnStruct>}
   */
    async getSelfFundAccountTypeData({ orgId, pageInfo, filter = null }) {
        const apiData = await getApiData(
            SelfDefFundAccountType.fromJson,
            orgId || Engine.profile.org.orgId,
            pageInfo,
            getSelfFundAccountType,
            filter,
            true
        );
        return apiData;
    }

    /**
     * 创建自定义资金账户类型
     * @param {string} name - Account type name
     * @param {string} code - Account type code
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async createSelfFundAccountType(name, code, orgId) {
        const res = await createSelfFundAccountType(name, code, orgId || Engine.profile.org.orgId);
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

    /**
     * 更新自定义资金账户类型
     * @param {string} id - Account type ID
     * @param {string} name - Account type name
     * @param {string} code - Account type code
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async updateSelfFundAccountType(id, name, code, orgId) {
        const res = await updateSelfFundAccountType(id, name, code, orgId || Engine.profile.org.orgId);
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

    /**
     * 删除自定义资金账户类型
     * @param {string} id - Account type ID
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async deleteSelfFundAccountType(id, orgId) {
        const res = await delSelfFundAccountType(id, orgId || Engine.profile.org.orgId);
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

     /**
     * 获取往来其他费用类型列表数据
     * @param {Object} options
     * @param {string} options.orgId - Organization ID
     * @param {DataPage} options.pageInfo - Pagination information
     * @param {Object} [options.filter] - Filter conditions
     * @returns {Promise<ApiReturnStruct>}
     */
    async getOtherFeeTypeData({ orgId, pageInfo, filter = null }) {
        const apiData = await getApiData(
            OtherFeeType.fromJson,
            orgId || Engine.profile.org.orgId,
            pageInfo,
            getOtherFeeTypeData,
            filter,
            true
        );
        return apiData;
    }

    /**
     * 创建往来其他费用类型
     * @param {string} name - 费用类型名称
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async createOtherFeeType(name, code, orgId) {
        const res = await createOtherFeeType(name,code, orgId || Engine.profile.org.orgId);
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

    /**
     * 更新往来其他费用类型
     * @param {string} id - 费用类型 ID
     * @param {string} name - 费用类型名称
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async updateOtherFeeType(id, name, code, orgId) {
        const res = await updateOtherFeeType({id, name, code, orgId:(orgId || Engine.profile.org.orgId)});
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

    /**
     * 删除往来其他费用类型
     * @param {string} id - 费用类型 ID
     * @param {string} orgId - Organization ID
     * @returns {Promise<any>}
     */
    async deleteOtherFeeType(id, orgId) {
        const res = await delOtherFeeType(id, orgId || Engine.profile.org.orgId);
        const apiResult = NetworkParser.parseNetworkResult(res, null);
        return apiResult;
    }

    /**
 * 获取待收款单详情
 * @param {string} orgId - Organization ID
 * @param {string} orderId - The pending receive order ID to fetch
 * @returns {Promise<PendingReceiveOrder|null>} 
 */
async getPendingReceiveOrderDetailInfo(orgId, orderId) {
    if (TestConfig.receiptsOrderTest) {
        // 模拟延时（例如：500毫秒）
        await new Promise(resolve => setTimeout(resolve, 1000));
        /// 模拟数据
        const testSimulateData = new TestSimulateData();

        let orderData = testSimulateData.simPendingReceiveOrder();

        // 查找匹配的元素
        let order = orderData.find(item => item.id === orderId);
        if (order) {
            return order;
        }

        return testSimulateData.simPendingReceiveOrder()[0];
    } else {
        let res = await getPendingReceiveOrderDetailInfo( orgId ?? Engine.profile.org.orgId , orderId);

        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, PendingReceiveOrder.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }
}

/**
 * 获取待付款单详情
 * @param {string} orgId - Organization ID
 * @param {string} orderId - The pending payment order ID to fetch
 * @returns {Promise<PendingPaymentOrder|null>} 
 */
async getPendingPaymentOrderDetailInfo(orgId, orderId) {
    if (TestConfig.receiptsOrderTest) {
        // 模拟延时（例如：500毫秒）
        await new Promise(resolve => setTimeout(resolve, 1000));
        /// 模拟数据
        const testSimulateData = new TestSimulateData();

        let orderData = testSimulateData.simPendingPaymentOrder();

        // 查找匹配的元素
        let order = orderData.find(item => item.id === orderId);
        if (order) {
            return order;
        }

        return testSimulateData.simPendingPaymentOrder()[0];
    } else {
        let res = await getPendingPaymentOrderDetailInfo( orgId ?? Engine.profile.org.orgId, orderId);

        // 解析数据，利用 NetworkParser 解析分页数据
        const apiResult = NetworkParser.parseNetworkResult(res, PendingPaymentOrder.fromJson);

        if (apiResult.data != null) {
            return apiResult.data;
        } else {
            if (apiResult.resErr != null &&
                typeof apiResult.resErr === 'string') {
                MessageUtil.showErrorMsg(apiResult.resErr);
            }
            return null;
        }
    }
}
}